<template>
  <BasicModal @register="registerModal" title="上传文件" :width="950" @cancel="okModal" @ok="okModal">
    <div class="head-title-box">
      <div class="title">上传路径</div>
      <div class="ericLine"></div>
      <div class="path">
        <FolderOpenFilled style="color: #ffb32b; font-size: 20px;" />
        <div class="text">{{ dirNavigation }}</div>
      </div>
    </div>
    <div style="margin-top: 10px; overflow-y: scroll; height: 441px;">
      <a-upload
        :customRequest="customRequest"
        list-type="picture-card"
        v-model:fileList="fileList"
        :multiple="true"
        @change="handleChange"
        @remove="removeFile"
        @preview="handlePreview"
      >
        <!-- @dragleave="dragover" <div class="uploadBox" v-if="fileList == undefined || fileList.length == 0"> -->
          <div>
            <div class="text">选择文件</div>
          </div>
          <!-- <div class="prompt" v-if="!fileList?.length">
            <CloudUploadOutlined style="color: #4597C4; font-size: 50px;" />
            <div class="text">选择文件或者拖动文件上传</div>
          </div> -->
        <!-- </div> -->
        <!-- <div v-else>
          <div class="fileList">
            <div class="fileBox" v-for="(item, index) in fileList">
              <CloseCircleFilled class="deleteIcon" @click.stop="delButton(index)" />
              <div class="fileImg">
                <Image @click="imageClickHandler"
                  :src="item?.response?.result?.successList[0]?.url || 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'"
                />
                <div class="uploadStatus">
                  <template v-if="item?.response?.success"><CheckCircleOutlined class="icon" /></template>
                  <template v-else><CloseCircleOutlined class="icon2" /></template>
                </div>
              </div>
              <div class="text">{{ item.name }}</div>
            </div>
          </div>
        </div> -->
      </a-upload>
      <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <template #footer>
      <div class="footerBox">
        <!-- <a-button @click="aaa123">上传文件</a-button> -->
        <div class="uploadResult">
          <!-- <CheckCircleOutlined class="icon" />
          <div class="complete">上传已完成</div> -->
          <div class="total">共<span class="number">{{  fileList?.length || 0 }}</span>个文件</div>
          <div class="success">成功上传<span class="number">{{  successNum }}</span>个</div>
          <div class="fail">失败<span class="number">{{  failNum }}</span>个</div>
        </div>
      </div>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { BasicModal, useModalInner } from '/@/components/Modal';
import { ref, computed, defineProps } from 'vue';
import { useGlobSetting } from '/@/hooks/setting';
import type { UploadProps } from 'ant-design-vue';
import { uploadMyFile } from '/@/api/common/api';
import { delSingleFile } from '../data.api'
import {
  FolderOpenFilled,
  CloudUploadOutlined,
  CloseCircleFilled,
  CheckCircleOutlined,
  CloseCircleOutlined,
  PlusOutlined
} from '@ant-design/icons-vue';

interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  url?: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}

const props = defineProps({
  dirList: {
    type: Array,
    default: []
  }
});

const [registerModal, { closeModal }] = useModalInner();
const fileList = ref<any[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const emits = defineEmits(['success', 'register']);
const { uploadUrl, apiUrl } = useGlobSetting();
const uploadFileUrl = `${uploadUrl}${apiUrl}/file/manage/uploadByDir`;
//const uploadFileUrl = `${uploadUrl}/file/manage/uploadByDir`;  // 本地local环境使用IP，不需要加上apiUrl ！

const dirNavigation = computed(() => props.dirList.reduce((prev, next: any, index) => {
  const lastItem = index > 0 && index === props.dirList?.length - 1
  prev += `${next?.name} ${ !lastItem ? '/' : ''}`;
  return prev;
  }, '')
);

const successNum = computed(() => fileList.value?.reduce((prev, next: any) => {
          prev += next?.response?.result?.successList[0]?.fileId ? 1 : 0;
          return prev;
        }, 0)
      );
const failNum = computed(() => fileList.value?.reduce((prev, next: any) => {
          prev += next.status === 'error' || next.status === 'done' && next?.response && next?.response?.result?.failList?.length ? 1 : 0;
          return prev;
        }, 0)
      );

const handleChange = ({ fileList: newFileList }: FileInfo) => {
  //console.log("newFileList", newFileList);
  fileList.value = newFileList;
};

const customRequest = async (e: any) => {
  const { file } = e
  let url = uploadFileUrl
  const curDirListTemp = props.dirList
  const parentItem: any = curDirListTemp[curDirListTemp?.length - 1]
  url = url + `?dirId=${parentItem.id}`
  let formData = new FormData()
  //formData.append('dirId', parentItem.id)
  formData.append('file', file)
  // return new Promise((resolve, reject) => {
  uploadMyFile(url, formData).then((res: any) => {
        //console.log('uploadMyFile', res);
        if (res?.data?.result?.successList?.length) {
          e.onSuccess(res.data, e); 
        } else {
          e.onError();
        }
    }).catch((err) => {
     // 调用实例的失败方法通知组件该文件上传失败
      e.onError(err);
    });
  // });
}

const removeFile = (file) => {
  //console.log("删除文件--file", file)
  const fileId = file?.response?.result?.successList[0]?.fileId
  return new Promise(async function(resolve, reject){
    if(!fileId){  // 上传失败的文件直接删除本地的
      resolve(true)
      return
    }
    // 删除服务器文件
    const res = await delSingleFile({ id: fileId })
    //console.log("删除文件==res", res)
    const { data } = res
    if( data.code === 200) {
      resolve(true)
    }else{
      reject()
    }
  })
}

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
}

const handlePreview = async (file: UploadProps['fileList'][number]) => {
  //console.log("预览图片--file", file)
  const fileUrl = file?.response?.result?.successList[0]?.url
  if (!file.preview) {
    file.preview = fileUrl
  }
  previewImage.value = fileUrl
  previewVisible.value = true
  previewTitle.value = file.name
};

function okModal() {
  fileList.value = []
  emits('success')
  closeModal();
}

</script>

<style lang="less" scoped>
/deep/.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

/deep/.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.uploadState {
  background: rgba(27, 135, 194, 0.08);
  height: 40px;
  margin-bottom: 22px;
  display: flex;
  align-items: center;
  padding: 0 16px;

  .total {
    display: flex;
    align-items: center;
    margin-right: 17px;

    .icon {
      color: #7db7d6;
      margin-right: 5px;
    }

    .number {
      color: #1b719f;
      margin: 0 4px;
    }

    .fileSize {
      color: #1b719f;
      margin-left: 4px;
    }
  }

  .uploadProgress {
    display: flex;
    align-items: center;
    width: 225px;

    .icon {
      color: #499FFF;
      margin-right: 9px;
    }

    .text {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      width: 100px;
    }

    .ProgressBox {
      width: 160px;
      display: flex;
      justify-content: center;
    }
  }

  .uploadSpeed {
    display: flex;
    align-items: center;
    margin-left: 11px;

    .size {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin-right: 22px;
    }

    .speed {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin-right: 31px;
    }

    .tiem {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }
  }

  .cancelButton {
    width: 76px;
    height: 30px;
    border-radius: 16px;
    border: 1px solid rgba(22, 125, 181, 0.5);
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(22, 125, 181, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 6px;
    cursor: pointer;
  }
}

.head-title-box {
  display: flex;
  align-items: center;
  background: linear-gradient(180deg, #E8F3F8 0%, rgba(232, 243, 248, 0) 100%);
  height: 40px;
  border: 1px solid rgba(11, 121, 181, 0.6);
  padding: 0 13px;

  .title {
    color: #60A7CE;
    font-size: 14px;
    font-weight: 500;
    font-family: PingFangSC-Medium, PingFang SC;
  }

  .ericLine {
    width: 1px;
    height: 20px;
    background-color: #CCCCCC;
    margin: 0 14px;
  }

  .path {
    display: flex;

    .text {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin-left: 6px;
    }
  }
}
/deep/ .ant-upload{
    .prompt {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .text {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #60A7CE;
      }
    }
}

.fileList {
  padding: 0 20px;
  display: flex;
  flex-wrap: wrap;
  .fileBox {
    flex: 0 0 calc(14%);
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .deleteIcon {
      position: absolute;
      top: -10px;
      right: 6px;
      z-index: 1;
      font-size: 22px;
      color: rgba(107, 108, 109, 0.8);
      background-color: #ffffff;
      border-radius: 50%;
      display: none;
    }

    .fileImg {
      position: relative;
      width: 88px;
      height: 86px;
      border-radius: 4px;
      overflow: hidden;
      .uploadStatus{
        position: absolute;
        width: 15px;
        height: 15px;
        bottom: 3px;
        right: 3px;
        .icon {
          color: #56c89f;
        }
        .icon2 {
          color: #eb2f96;
        }
      }
    }
    .text {
      margin-top: 8px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      width: 88px;
      height: 40px;
      overflow: hidden;
      white-space: pre-wrap;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }

  .fileBox:hover {
    .deleteIcon {
      display: block;
    }
  }
}

.jeecg-modal-content /deep/ .scroll-container {
  padding: 0px;
}

.footerBox {
  display: flex;

  .uploadResult {
    color: #666666;
    display: flex;
    align-items: center;
    margin-left: 30px;
    .icon {
      color: #56c89f;
      margin-right: 5px;
    }
    .complete {
      margin-right: 18px;
    }
    .total {
      margin-right: 5px;
      .number {
        color: #156d9c;
      }
    }
    .success {
      margin-right: 5px;
      .number {
        color: #56c89f;
      }
    }
    .fail {
      .number {
        color: #ee5555;
      }
    }
  }
}

/deep/ .ant-upload-drag {
  background-color: #fafdff;
  border: 1px dashed #60A7CE;
}
/deep/ .ant-progress-line {
  line-height: 0px;
}</style>
